import javax.sound.sampled.*;

import edu.cmu.sphinx.frontend.util.Microphone;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

public class SpeechHandler {

	private Recognizer recognizer; 
	private boolean test;
	private int result;
	
	public SpeechHandler() {
		ConfigurationManager cm;

		cm = new ConfigurationManager(SpeechHandler.class.getResource("speech.config.xml"));

		recognizer = (Recognizer) cm.lookup("recognizer");
		recognizer.allocate();

		// start the microphone or exit if the programm if this is not possible
		Microphone microphone = (Microphone) cm.lookup("microphone");
		if (!microphone.startRecording()) {
			System.out.println("Cannot start microphone.");
			recognizer.deallocate();
		}
		
		
		/*Runnable r = new Runnable() {
			public void run() {
				while(true) {
					if(test) {
						setVolume(re);
					}
				}
			}
		};
		Thread th = new Thread(r);
		
		th.start();
		*/
	}
	
	private float volume;
	public int getVolume() {
		int vol = (int) (volume / 1000);
		System.out.println("Volume: " + vol);
		return vol;
	}
	
	private void setVolume(Result inVolume) {
		float logVolume = inVolume.getBestActiveToken().getAcousticScore();
		volume = (logVolume);
	}
/*
	static Line getLine(Line.Info info)
	
	TargetDataLine line;
	DataLine.Info info1 = new DataLine.Info(TargetDataLine.class, 
	    format); // format is an AudioFormat object
	if (!AudioSystem.isLineSupported(info1)) {
	    // Handle the error ... 

	}
	// Obtain and open the line.
	try {
	    line = (TargetDataLine) AudioSystem.getLine(info1);
	    line.open(format);
	} catch (LineUnavailableException ex) {
	    // Handle the error ... 
	}
	*/

	public int getAction() {
		Result result = recognizer.recognize();

		int out = BunnyAction.NULL;
		if (result != null) {
			String resultText = result.getBestFinalResultNoFiller();
			System.out.println(resultText);

			if(resultText.equals("up")) {
				out = BunnyAction.UP;
			} else if(resultText.equals("right")) {
				out = BunnyAction.RIGHT;
			} else if(resultText.equals("down")) {
				out = BunnyAction.DOWN;
			} else if(resultText.equals("left")) {
				out = BunnyAction.LEFT;
			} else if(resultText.equals("stop")) {
				out = BunnyAction.NULL;
			}
			System.out.println("Direction: " + resultText);
		}
		setVolume(result);
		return out;
	}
}
